package service

import (
	"GoMaestro/internal/entity"
	jenkins "GoMaestro/internal/jencli"
	"github.com/gin-gonic/gin"
)

type JenServiceImp struct {
	//	暂不匹配dao层，当前jenkins的操作是基于http请求的，不需要dao层
}

func NewJenServiceImp() *JenServiceImp {
	return &JenServiceImp{}
}

func (j JenServiceImp) GetNodeStatus() (*entity.JenNodes, error) {
	status, err := jenkins.GetJenNodeStatus()
	return status, err
}

func (j JenServiceImp) GetBuildStatus(s string, i int) (interface{}, error) {
	status, err := jenkins.GetBuildStatus(s, i)
	return status, err
}

func (j JenServiceImp) GetJobLog(job string, s1 int64, s2 ...string) (interface{}, error) {
	log, err := jenkins.GetJenkinsBuildLog(job, s1, s2...)
	return log, err
}

func (j JenServiceImp) CreateTask(s string, m map[string]string) (int64, string, error) {
	task, s2, err := jenkins.CreateBuildTask(s, m)
	return task, s2, err
}

func (j JenServiceImp) GetStreamLog(c *gin.Context, job string, s1 int64, logChan chan string, errChan chan error, s2 ...string) {
	go func() {
		defer close(logChan) // 确保 goroutine 退出时关闭通道
		defer close(errChan)

		success := jenkins.StreamJenkinsBuildLog(job, s1, logChan, errChan, s2...)
		// 如果 StreamJenkinsBuildLog 返回 false，说明发生错误
		if !success {
			select {
			case err := <-errChan: // 使用 select 进行非阻塞接收
				if err != nil { // 检查 nil，避免 panic
					c.JSON(500, gin.H{"error": err.Error()})
				}
			default:
				c.JSON(500, gin.H{"error": "发生未知错误"})
			}
		}
	}()
}

var AppJenServiceImp = NewJenServiceImp()
